// pages/leader/leader.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leader: null,
    openid: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var leader = options.leader;
    var openid = this.data.openid;
    this.setData({leader:leader})
   
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  getUserInfo: function (e) {
    var that = this;
    //获取code
    wx.login({
      success: function (res) {
        wx.request({
          url: app.globalData.apiUrl + "/api/user/login/",
          data: { code: res.code, nickname: e.detail.userInfo.nickName, avatar: e.detail.rawData },
          method: 'POST',
          dataType: 'json',
          success: function (res) {
            app.globalData.openid = res.data.openid;//保存到全局
            app.globalData.userInfo = res.data
            console.log(app.globalData.openid)
            try {
              wx.setStorageSync('openid', res.data.openid)
              that.setData({ openid: res.data.openid })
            } catch (e) {
              console.log(e);
            }
            wx.showToast({
              title: '登入成功',
              icon: 'none'

            })
            //添加代理
            var openid = that.data.openid;
            var leader = that.data.leader;
            wx.request({
              url: app.globalData.apiUrl + '/api/user/addLeader',
              data: { openid: openid, leader: leader },
              method: 'GET',
              dataType: 'json',
              success: function (res) {
                console.log(res)
              },
              fail: function (res) { },
              complete: function (res) { },
            })
            wx.switchTab({
              url: '/pages/index/index'
            })
          },
          fail: function (res) {
            wx.showToast({
              title: '服务器错误',
              icon: 'none'
            })
          },
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
    console.log(e.detail.userInfo)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
})